<template>
  <w-modal ref="WModal" title="修改用户" @ok="okBtnClick">
    <div class="w-flex-center">
      <w-image-up ref="WImageUp" :souce-url="icon" />
    </div>
    <br>
    <a-form :form="form" :label-col="{ span: 2 }" :wrapper-col="{ span: 22 }">
      <a-form-item label="账户">
        <a-input
          v-decorator="['user', { rules: [{ required: true, message: '请输入用户名', }], initialValue: userName }]"
          placeholder="设置账户..."
        />
      </a-form-item>
      <a-form-item label="密码">
        <a-input
          v-decorator="['pass', { rules: [{ required: true, message: '请输入密码' }] }]"
          placeholder="设置账户..."
        />
      </a-form-item>
    </a-form>
  </w-modal>
</template>

<script lang="ts">
import { Vue, Component, Prop } from 'vue-property-decorator'
import { Getter } from 'vuex-class'
import { WrappedFormUtils } from 'ant-design-vue/types/form/form'
import WImageUp, { OssImageUpType } from '@/components/global/imageUp/oss'
import WModal, { ModalComType } from '@/components/global/modal'

@Component({
  name: 'ComAdminAuthEditUserPop',
  components: {
    WImageUp,
    WModal
  },
  data () {
    return {
      form: this.$form.createForm(this, { name: 'coordinated' })
    }
  }
})
export default class ComAdminAuthEditUserPop extends Vue {
  // 是否是当前用户
  @Prop({ type: Boolean, default: true }) current!: boolean;

  @Getter('auth/USER_ICON') userIcon!: string;
  @Getter('auth/USER') userName!: string;

  form!: WrappedFormUtils;

  icon = '';

  /**
   * 显示数据
   */
  show () {
    (this.$refs.WModal as ModalComType).show()
    this.icon = this.current ? this.userIcon : ''
  }

  /**
   * 确定按钮点击
   */
  okBtnClick () {
    (this.$refs.WModal as ModalComType).showLoading()
    this.check()
      .then((data) => {
        this.$store
          .dispatch('auth/UPDATE_USER', data)
          .then(() => {
            if (this.current) {
              this.$message.success('修改成功，请重新登录')
              this.$store
                .dispatch('auth/LOGOUT')
                .then(() => {
                  this.$router.replace('/login')
                })
                .catch(() => {})
            }
          })
          .catch(() => {})
          .finally(() => {
            (this.$refs.WModal as ModalComType).hideLoading()
          })
      })
      .catch(() => {
        (this.$refs.WModal as ModalComType).hideLoading()
      })
  }

  /**
   * 校验输入的数据
   */
  check () {
    return new Promise((resolve, reject) => {
      this.form.validateFields((err, values) => {
        if (!err) {
          (this.$refs.WImageUp as OssImageUpType)
            .upImage()
            .then((icon) => {
              resolve({
                icon,
                ...values
              })
            })
            .catch(() => {
              reject(err)
            })
        } else {
          reject(new Error())
        }
      })
    })
  }
}
</script>

<style scoped></style>
